<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Article as Model;
use app\common\model\ArticleCategory as CategoryModel;
use app\common\model\Check;
use app\common\model\Reward;
use app\common\model\User;
use app\common\model\Upload as UploadModel;

class Article extends AdminBase
{
    protected $categoryModel;
    protected $model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->categoryModel = new CategoryModel();
        $this->model = new Model();
        $category_level_list = $this->categoryModel->catetree();
        $this->assign('category_level_list', $category_level_list);
    }

    public function index()
    {
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $perpage = isset($_REQUEST['perpage']) ? $_REQUEST['perpage'] : 10;
        $keyword = isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';
        $category_id = isset($_REQUEST['category_id']) ? trim($_REQUEST['category_id']) : 0;
        $status = isset($_REQUEST['status']) ? trim($_REQUEST['status']) : '';
        $is_essence = isset($_REQUEST['is_essence']) ? trim($_REQUEST['is_essence']) : '';
        $is_carousel = isset($_REQUEST['is_carousel']) ? trim($_REQUEST['is_carousel']) : '';
        $is_ad = isset($_REQUEST['is_ad']) ? trim($_REQUEST['is_ad']) : '';
        $startdate = isset($_REQUEST['startdate']) ? trim($_REQUEST['startdate']) : '';
        $enddate = isset($_REQUEST['enddate']) ? trim($_REQUEST['enddate']) : '';
        $map = [];

        if ($keyword) {
            $map['title|f.keywords'] = ['like', "%{$keyword}%"];
        }
        if ($category_id != '') {
            $map['f.category_id'] = $category_id;
        }

        if ($status != '') {
            $map['f.status'] = $status;
        }
        if ($is_essence != '') {
            $map['is_essence'] = $is_essence;
        }
        if ($is_ad != '') {
            $map['is_ad'] = $is_ad;
        }
        if ($is_carousel != '') {
            $map['is_carousel'] = $is_carousel;
        }
        if ($keyword) {
            $map['title|f.keywords'] = ['like', "%{$keyword}%"];
        }
        if ($startdate) {
            $map['time'] = ['egt', strtotime($startdate)];
        }
        if ($enddate) {
            $map['time'] = ['elt', strtotime($enddate . ' 23:59:59')];
        }

        $article_list = $this->model->alias('f')->join('article_category c', 'c.id=f.category_id')->join('user u', 'u.id=f.user_id', 'left')->field('f.*,u.username,c.name')->order('f.id desc')->where($map)->paginate($perpage);

        $this->assign(array('is_ad' => $is_ad, 'is_carousel' => $is_carousel, 'is_essence' => $is_essence, 'status' => $status, 'category_id' => $category_id, 'keyword' => $keyword, 'startdate' => $startdate, 'enddate' => $enddate, 'perpage' => $perpage));
        return $this->fetch('index', ['article_list' => $article_list]);
    }

    public function add()
    {
        return view();
    }

    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $title = remove_xss($data['title']);
            $data['title'] = $title;
            $data['uniquekey'] = md5($title);
            if ($this->model->where('uniquekey', $data['uniquekey'])->find()) {
                return json(array('code' => 0, 'msg' => '已发布相同标题的文章'));
            }
            $data['updated_at'] = date('Y-m-d H:i:s');
            if ($data['publish_time'] > $data['updated_at']) {
                $data['status'] = 0; //定时发布
            } else {
                $data['publish_time'] = $data['updated_at'];
            }
            if($data['color']) {
                if (substr($data['color'], 0, 1) != '#' && strlen($data['color']) != 7) {
                    return json(array('code' => 0, 'msg' => '颜色格式不正确,必须#开始,7位'));
                }
            }
            if (!$data['activity_finish_time']) {
                unset($data['activity_finish_time']);
            }
            if ($data['cover_img'] == '') {
                //获取第一张图为封面图
                $data['cover_img'] = get_coverpic($data['content']);
            }
            if ($data['down_link1']) {
                $data['has_attachment'] = 1;
            }
            $res = $this->model->allowField(true)->save($data);
            if ($res) {
                (new User())->where('id', 1)->setInc('posted_num');
                (new User())->where('id', 1)->setInc('passed_num');
                return json(array('code' => 200, 'msg' => '提交成功'));
            } else {
                return json(array('code' => 0, 'msg' => '提交失败'));
            }

        }
    }

    public function toggle($id, $status, $name)
    {
        if ($this->request->isGet()) {

            if ($this->model->where('id', $id)->update([$name => $status]) !== false) {
                //  $this->success('更新成功');
                return json(array('code' => 200, 'msg' => '更新成功'));
            } else {
                // $this->error('更新失败');
                return json(array('code' => 0, 'msg' => '更新失败'));
            }
        }

    }

    /**
     * 编辑分类
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {

        $tptc = $this->model->find($id);
        //查看审核信息
        $checkInfo = (new Check())->where('object_type', 1)
            ->where('object_id', $id)->find();
        if ($checkInfo && !$checkInfo['remark']) {
            $checkInfo['remark'] = '审核通过';
        }
        $reward['alipay_name'] = $reward['alipay_account'] = '';
        $reward = (new Reward())->where('object_type', 1)
            ->where('object_id', $id)->find();

//        if ($checkInfo && !$checkInfo['remark']) {
//            $Reward['rewardInfo'] = '审核通过';
//        }
        return $this->fetch('edit', ['article' => $tptc, 'rewardInfo' => $reward]);

    }

    /**
     * 更新分类
     * @throws \think\Exception
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $title = remove_xss($data['title']);
            $data['title'] = $title;
            if ($this->model->where('title', $data['title'])->where('id', 'neq', $data['id'])->find()) {
                return json(array('code' => 0, 'msg' => '已发布相同标题的文章'));
            }
            $data['updated_at'] = date('Y-m-d H:i:s');
            if ($data['publish_time'] > $data['updated_at']) {
                $data['status'] = 0; //定时发布
            } else {
                $data['publish_time'] = $data['updated_at'];
            }
            if($data['color']) {
                if (substr($data['color'], 0, 1) != '#' && strlen($data['color']) != 7) {
                    return json(array('code' => 0, 'msg' => '颜色格式不正确,必须#开始,7位'));
                }
            }
            if ($data['down_link1']) {
                $data['has_attachment'] = 1;
            } else {
                $data['has_attachment'] = 0;
            }
            if (!$data['activity_finish_time']) {
                unset($data['activity_finish_time']);
            }
            if (@$data['check_status'] == 1) {
                $data['status'] = 1;
            }else{
                if (@$data['check_status'] == 2) {
                    $data['status'] = 2;
                }
            }
            if ($data['cover_img'] == '') {
                //获取第一张图为封面图
                $data['cover_img'] = get_coverpic($data['content']);
            }
            $res = $this->model->allowField(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                if (isset($data['check_status'])) {
                    if ($data['check_status'] == 1) {
                        (new User())->where('id', $data['user_id'])->setInc('passed_num');
                    }
                }
                return json(array('code' => 200, 'msg' => '更新成功'));
            } else {
                return json(array('code' => 0, 'msg' => '更新失败'));
            }
        }
    }

    /**
     * 删除分类
     * @param $id
     * @throws \think\Exception
     */
    public function delete($id)
    {

        $info = $this->model->find($id);


        if ($this->model->destroy($id)) {

            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }

    public function alldelete()
    {
        $params = input('post.');


        $ids = implode(',', $params['ids']);
        $result = $this->model->destroy($ids);
        if ($result) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }

    public function setClick()
    {
        $params = input('post.');
        foreach ($params['ids'] as $k => $v) {
            $info = $this->model->find($v);
        }

        $ids = implode(',', $params['ids']);
        $result = $this->model->destroy($ids);
        if ($result) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }

    public function pullnew()
    {
        $res = Model::syncFromLaysns(30);
        return json(array('code' => 0, 'msg' => $res['msg']));
    }
}
